package com.tqz.web.flux.demo.function;

import com.tqz.web.flux.demo.entity.User;
import com.tqz.web.flux.demo.exception.CustomException;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.Optional;

/**
 * <p>webflux中的每一个handler相当于web mvc中controller中的每一个方法，输入为请求体，输出封装在mono中。
 *
 * @author tianqingzhao
 * @since 2023/3/4 20:45
 */
@Component
public class UserHandler {

    @NotNull
    public Mono<ServerResponse> getUser(ServerRequest request) {
        Optional<String> optionalId = request.queryParam("id");

        int id = Integer.parseInt(optionalId.orElse("1"));

        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(Mono.just(new User((id), "zhangsan")).map(this::check), User.class);
    }

    private User check(User user) {
        // 模拟异常
        if (user.getId() == 10) {
            throw new CustomException("throw my exception.");
        }
        return user;
    }
}
